package com.syyo.gulimall.seckill.interceptor;

import com.syyo.common.constant.AuthConstant;
import com.syyo.common.vo.MemberVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ author: wang
 * @ date: 2021/4/26 14:28
 * @ Description:  登录拦截器
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {


    public static ThreadLocal<MemberVo> loginUser = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行订单服务
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/kill", uri);

        if (match) {
            MemberVo attribute = (MemberVo) request.getSession().getAttribute(AuthConstant.LOGIN_USER);
            if (attribute == null) {
                // 没登录
                request.getSession().setAttribute("msg", "请先登录");

                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            } else {
                // 放入线程
                loginUser.set((MemberVo) attribute);
                return true;
            }
        }
        return true;
    }
}
